from selenium import webdriver
import time
from PIL import Image   # 操作图片

# # 实现无可视化操作
# chrome_option = webdriver.chrome.options.Options()
# chrome_option.add_argument('--headless')
# chrome_option.add_argument('--disable-gpu')

# 创建浏览器对象并打开12306登陆界面
url = 'https://kyfw.12306.cn/otn/resources/login.html'
bro = webdriver.Chrome(executable_path='web_爬虫\chromedriver.exe')#, chrome_options=chrome_option)
bro.get(url)
# bro.execute_script("document.body.style.transform='scale(0.8)'")    # 缩放80%
# bro.maximize_window()
time.sleep(5)
# 点击切换为账号密码登陆
span = bro.find_element_by_xpath('/html/body/div[2]/div[2]/ul/li[2]/a')
span.click()

# 定位输入框输入账号密码
user_name = bro.find_element_by_id('J-userName')
user_pwd = bro.find_element_by_id('J-password')
user_name.send_keys('10000000')
user_pwd.send_keys('12345678')

### 验证码识别点击模块
bro.save_screenshot('aa.png')   # 对打开的整张页面进行截图保存
# 截取验证码部分图片（确定验证码所在标签的左上角和右下角坐标）
code_img_ele = bro.find_element_by_id('J-loginImg') # 标签定位
location = code_img_ele.location    # 返回验证码图片左上角的坐标 x,y
size = code_img_ele.size    # 返回验证码标签对应的长和宽
# 得到验证码的两个角的坐标
rangle = (
    int(location['x']), int(location['y']),
    int(location['x'])+int(size['width']), int(location['y'])+int(size['height'])
)
image = Image.open('aa.png')
# 对指定区域进行裁剪
frame = image.crop(rangle)  
frame.save('code.png')

# TODO 将图片提交超级鹰识别并返回结果坐标后进行点击验证

# 点击登陆按钮
login_btn = bro.find_element_by_id('J-login')
login_btn.click()

# time.sleep(3)
bro.quit()
